package com.weiaibenpao.demo.chislim.ui.activity.moment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.bean.Comment;
import com.weiaibenpao.demo.chislim.bean.Moment;
import com.weiaibenpao.demo.chislim.bean.MomentDetailsBean;
import com.weiaibenpao.demo.chislim.bean.MomentEvent;
import com.weiaibenpao.demo.chislim.bean.Praise;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.MomentDetailsPresenter;
import com.weiaibenpao.demo.chislim.ui.activity.me.UserZoneActivity;
import com.weiaibenpao.demo.chislim.ui.widget.MomentActionDialog;
import com.weiaibenpao.demo.chislim.ui.widget.MomentView;
import com.weiaibenpao.demo.chislim.ui.widget.ReportSelectDialog;
import com.weiaibenpao.demo.chislim.utils.Utils;
import com.weiaibenpao.demo.chislim.view.MomentDetailsView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MomentDetailsActivity extends BaseActivity<MomentDetailsView,MomentDetailsPresenter> implements MomentDetailsView{
    public static final int REQUEST_MOMENT_DETAIL = 101;
    public static final int MAX_DISPLAY_COUNT = 8;
    public static final String MOMENT = "moment";
    public static final String MOMENT_ID = "moment_id";
    public static final String USER_ID = "user_id";
    public static final String POSITION ="position";
    private Moment mMoment;
    private int mItemPosition;
    private int mUserId;
    private int mMomentId;
    private int mNextPage = 1;
    private int parentId = -1;
    @BindView(R.id.content)
    ScrollView content;
    @BindView(R.id.momentView)
    MomentView mMomentView;
    @BindView(R.id.tv_like_count)
    TextView mTvLikeCount;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.comment_container)
    LinearLayout mCommentContainer;
    @BindView(R.id.user_header_container)
    LinearLayout mHeaderContainer;
    @BindView(R.id.send_et)
    EditText mEtInput;
    @BindView(R.id.send_tv)
    TextView tvSend;

    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_moment_details;
    }

    @Override
    public MomentDetailsPresenter initPresenter() {
        return new MomentDetailsPresenter();
    }

    @Override
    public void init(Bundle savedInstanceState) {
        // 奇了怪了，这版项目中必须XML中设置fitsSystemWindows为true 底部输入框自动顶上去才起作用。。
        // 1.考虑到用户还少，评论这版不做分页，一次性返回所有评论
        // 2.删除或者添加评论成功后回到列表本应该更新相应评论数字，但是由于实时性要求不强暂不做。。
        if (getIntent() != null) {
            mUserId = getIntent().getIntExtra(USER_ID,-1);
            mMomentId = getIntent().getIntExtra(MOMENT_ID,-1);
            mMoment = getIntent().getParcelableExtra(MOMENT);
            mItemPosition = getIntent().getIntExtra(POSITION,-1);
            if(mMoment != null){
                mUserId = mMoment.getUserId();
                mMomentId = mMoment.getId();
                setMoment(mMoment);
            }
        }
        mPresenter.getMomentDetails(mUserId,mMomentId,mNextPage);
        content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Utils.hideSoftInput(MomentDetailsActivity.this, content);
                mEtInput.setHint(getString(R.string.add_comment_hint));
                parentId = -1;
                Logger.e("MomentDetailsActivity----onTouch");
                return false;
            }
        });
    }

    private void setMoment(Moment moment) {
        if (moment != null) {
            mMomentView.setApplyType(MomentView.TYPE_MOMENT_DETAIL);
            mMomentView.setView(moment);
            mMomentView.disableRootClick();//解决详情页点击到Moment区域键盘不消失，因为拦截了content的touch事件
            mMomentView.hideFooter();
            mTvLikeCount.setText(getString(R.string.people_liked,String.valueOf(moment.getLikeNum())));
            if(!TextUtils.isEmpty(moment.getHumorpalce())) mTvLocation.setText(getString(R.string.from_location,moment.getHumorpalce()));
        }
    }

    private void setCommentList(List<Comment> commentList) {
        if (commentList == null) {
            return;
        }
        int commentNum = commentList.size();
        for (int i = 0; i < commentNum; i++) {
            insertComment(commentList.get(i));
        }
    }

    private void setPraisedList(List<Praise> praisedList) {
        if (praisedList == null) {
            return;
        }
        int displayCount = praisedList.size() >= MAX_DISPLAY_COUNT ? MAX_DISPLAY_COUNT : praisedList.size();
        for(int i=0;i<displayCount;i++){
            final Praise praise = praisedList.get(i);
            View view = LayoutInflater.from(this).inflate(R.layout.item_praise_small_header, mHeaderContainer, false);
            ImageView header = (ImageView) view.findViewById(R.id.avatar);
            mHeaderContainer.addView(view);
            loadImage(praise.getUserImage(), header);
            header.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserZoneActivity.startSelf(MomentDetailsActivity.this,praise.getUserId());
                }
            });
        }
        if (displayCount == MAX_DISPLAY_COUNT) {
            View moreParent = LayoutInflater.from(this).inflate(R.layout.item_praise_small_header, mHeaderContainer, false);
            ImageView more = (ImageView) moreParent.findViewById(R.id.avatar);
            more.setImageResource(R.drawable.img_moment_detail_more);
            mHeaderContainer.addView(moreParent);
            more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LikerListActivity.startSelf(MomentDetailsActivity.this,mMomentId);
                }
            });
        }
    }

    private void loadImage(String url, ImageView imageView) {
        if (imageView == null) {
            return;
        }
        if(isDestroyed()){
            return;
        }
        Glide
                .with(this)
                .load(url)
                .into(imageView);
    }

    private void insertComment(final Comment comment) {
        final TextView tvComment = (TextView) LayoutInflater.from(this).inflate(R.layout.item_user_comment, mCommentContainer, false);
        final String userName = comment.getUserName();
        String otherUsername = comment.getPreUserName();
        SpannableStringBuilder content;
        if (TextUtils.isEmpty(otherUsername)) { //这是一条评论
            String targetStr = userName + getString(R.string.colon);
           content = Utils.getBoldColorStr(targetStr+comment.getComText(),targetStr.length(),getResources().getColor(R.color.colorParagraph));
        } else { //这是一条回复其他评论者的评论
            String secondTargetStr = otherUsername + getString(R.string.colon);
            int replyStrWithSpaceSize = getString(R.string.reply).length()+2;//2为前后两个空格
            content = Utils.getDoubleBoldColorStr(userName + getString(R.string.space)+getString(R.string.reply)+getString(R.string.space)+secondTargetStr+comment.getComText(),
                    0,userName.length(),
                    userName.length()+replyStrWithSpaceSize,userName.length()+replyStrWithSpaceSize+ secondTargetStr.length(),
                    getResources().getColor(R.color.colorParagraph));
        }
        tvComment.setText(content);
        tvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int mineId = UserPreferences.getInstance().getInt(UserPreferences.USER_ID);
                if (mineId != comment.getUserId()) {
                    Utils.showSoftInput(tvComment.getContext());
                    mEtInput.setHint(getString(R.string.reply) + userName + getString(R.string.colon));
                    mEtInput.requestFocus();
                    parentId = comment.getId();
                    Logger.e("onClick--parent id " + parentId);
                } else {
                    Logger.e("onClick--delete comment");
                    MomentActionDialog actionDialog = new MomentActionDialog(MomentDetailsActivity.this,MomentActionDialog.ACTION_DELETE);
                    actionDialog.setOnActionClickListener(new MomentActionDialog.OnActionClickListener() {
                        @Override
                        public void onActionClicked(String action) {
                            mPresenter.deleteComment(mineId,comment.getId());
                        }
                    });
                    actionDialog.show();
                }
            }
        });
        tvComment.setTag(comment.getId());
        mCommentContainer.addView(tvComment);
    }

    @OnClick({R.id.left_image,R.id.send_tv,R.id.more})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.left_image:
                finish();
                break;
            case R.id.send_tv:
                if (!Utils.isNetWorkConnected()) {
                    Toast.makeText(this, getString(R.string.network_not_connected), Toast.LENGTH_SHORT).show();
                    return;
                }
                tvSend.setClickable(false);
                String inputText = String.valueOf(mEtInput.getText()).trim();//如果不trim() 用户按一下空格键也会被认为不空，所以会看到评论区冒号后面啥都没有的现象，实际上还是有内容的，只是空格而已！
                if (!TextUtils.isEmpty(inputText)) {
                    int mineId = UserPreferences.getInstance().getInt(UserPreferences.USER_ID);
                    if (parentId >= 0) {
                        mPresenter.replyComment(mineId,parentId,mMomentId,inputText);
                    } else {
                        mPresenter.addComment(mineId,mMomentId,inputText);
                    }
                }else {
                    Toast.makeText(this, getString(R.string.no_send_empty), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.more:
                handleClickMore(mItemPosition,mMoment);
                break;
        }
    }

    public static void startSelf(Activity activity,int momentId ,int userId){
        Intent intent = new Intent(activity,MomentDetailsActivity.class);
        intent.putExtra(USER_ID,userId);
        intent.putExtra(MOMENT_ID,momentId);
        activity.startActivity(intent);
    }

    public static void startSelf(Activity activity, Moment moment, int position) {
        Intent intent = new Intent(activity, MomentDetailsActivity.class);
        intent.putExtra(MOMENT, moment);
        intent.putExtra(POSITION,position);
        activity.startActivityForResult(intent, REQUEST_MOMENT_DETAIL);
    }

    @Override
    public void onGetMomentDetailsSuccess(MomentDetailsBean momentDetailsBean) {
        setMoment(momentDetailsBean.getHumor());
        setPraisedList(momentDetailsBean.getPraiselist());
        setCommentList(momentDetailsBean.getCommentlist());
        Logger.e("onGetMomentDetailsSuccess");
    }

    @Override
    public void onGetMomentDetailsFailed(String errMsg) {
        Logger.e("onGetMomentDetailsFailed----->"+errMsg);
    }

    @Override
    public void onAddCommentSuccess(Comment comment) {
        doInsertComment(comment);
        Logger.e("onAddCommentSuccess");
    }

    private void doInsertComment(Comment comment) {
        tvSend.setClickable(true);
        insertComment(comment);
        mEtInput.setText("");
        Utils.hideSoftInput(MomentDetailsActivity.this, mEtInput);
        scrollToBottom();
    }

    @Override
    public void onAddCommentFailed(String errMsg) {
        tvSend.setClickable(true);
        Toast.makeText(this,getString(R.string.comment_failed),Toast.LENGTH_LONG).show();
        Logger.e("onAddCommentFailed----->"+errMsg);
    }

    @Override
    public void onReplyCommentSuccess(Comment comment) {
        doInsertComment(comment);
        Logger.e("onReplyCommentSuccess");
    }

    @Override
    public void onReplyCommentFailed(String errMsg) {
        tvSend.setClickable(true);
        Toast.makeText(this,getString(R.string.comment_failed),Toast.LENGTH_LONG).show();
        Logger.e("onReplyCommentFailed----->"+errMsg);
    }

    @Override
    public void onReportSuccess() {
        Toast.makeText(this,getString(R.string.thank_you_for_reporting),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDeleteSuccess(int position) {
        Logger.e("onDeleteSuccess--"+position);
        MomentEvent momentEvent = new MomentEvent();
        momentEvent.setDelete(true);
        momentEvent.setDeletePosition(position);
        EventBus.getDefault().postSticky(momentEvent);
        finish();
    }

    @Override
    public void onDeleteCommentSuccess(int tag) {
        Logger.e("onDeleteCommentSuccess");
        if(mCommentContainer != null){
            View view = mCommentContainer.findViewWithTag(tag);
            mCommentContainer.removeView(view);
        }
    }

    private void scrollToBottom() {
        content.post(new Runnable() {
            @Override
            public void run() {
                content.fullScroll(View.FOCUS_DOWN);
            }
        });
    }


    private void handleClickMore(final int position, final Moment moment) {
        String action;
        if(UserPreferences.getInstance().getInt(UserPreferences.USER_ID) == moment.getUserId()){
            action = MomentActionDialog.ACTION_DELETE;
        }else {
            action = MomentActionDialog.ACTION_REPORT;
        }
        MomentActionDialog momentActionDialog = new MomentActionDialog(this,action);
        momentActionDialog.setOnActionClickListener(new MomentActionDialog.OnActionClickListener() {
            @Override
            public void onActionClicked(String action) {
                Logger.e("onActionClicked----"+action);
                if(MomentActionDialog.ACTION_DELETE.equals(action)){
                    mPresenter.deleteMoment(moment.getUserId(),moment.getId(),position);
                }else {
                    ReportSelectDialog reportSelectDialog = new ReportSelectDialog(MomentDetailsActivity.this);
                    reportSelectDialog.setOnReportSelectListener(new ReportSelectDialog.OnReportSelectListener() {
                        @Override
                        public void onSelected(String content) {
                            mPresenter.report(UserPreferences.getInstance().getInt(UserPreferences.USER_ID),moment.getId(),0,content);
                        }
                    });
                    reportSelectDialog.show();
                }
            }
        });
        momentActionDialog.show();
    }
}
